#include <string.h>
#include <stdlib.h>
#include <errno.h>
#include <sys/types.h>
#include <unistd.h>
#include <time.h>
#include <stdio.h>
#include <net/if.h>
#include <arpa/inet.h>
#include <sys/socket.h>
#include <linux/rtnetlink.h>
#include "head.h"
using namespace std;

int setroute(int action, string net,string mask,string gw,string dev="eth0")
{
    struct rtentry route;
    char target[128] = {0};
    char gateway[128] = {0};
    char netmask[128] = {0};

    struct sockaddr_in *addr;

    int skfd;

    memset((char *)&route, 0x00, sizeof(route));

    route.rt_flags = RTF_UP ;

    
    strcpy(target,net.c_str());
    addr = (sockaddr_in*) &route.rt_dst;
    addr->sin_family = AF_INET;
    addr->sin_addr.s_addr = inet_addr(target);


    strcpy(netmask,mask.c_str());
    addr = (sockaddr_in*) &route.rt_genmask;
    addr->sin_family = AF_INET;
    addr->sin_addr.s_addr = inet_addr(netmask);

    strcpy(gateway, gw.c_str());
    addr = (struct sockaddr_in*) &route.rt_gateway;
    addr->sin_family = AF_INET;
    addr->sin_addr.s_addr = inet_addr(gateway);
    route.rt_flags |= RTF_GATEWAY;

    route.rt_dev = (char *)dev.c_str();
    skfd = socket(AF_INET, SOCK_DGRAM, 0);
    if(skfd < 0)
    {
        perror("socket");
        return 0;
    }

    if(action == RTACTION_DEL)
    {
        if(ioctl(skfd, SIOCDELRT, &route) < 0)
        {
            perror("SIOCDELRT");
            close(skfd);
            return 0;
        }
    }
    else
    {
        if(ioctl(skfd, SIOCADDRT, &route) < 0)
        {
            perror("SIOCADDRT");
            close(skfd);
            return 0;
        }
    }
    (void) close(skfd);
    return 1;
}

int distence_vector(vector<route_row> &fore_table,vector<route_row> local_table)
{
    for(auto &fore:fore_table)
    {
        fore.metric++;
    }
    unordered_map<string,int> hmap;
    for(int i=0;i<local_table.size();i++)
    {
        hmap[local_table[i].dest] = i;
    }
    for(auto fore:fore_table)
    {
        if(hmap.count(fore.dest))
        {
            route_row lt = local_table[hmap.find(fore.dest)->second];
            if(fore.nextjump==lt.nextjump)
            {
                setroute(RTACTION_DEL,(string)fore.dest,(string)fore.mask,(string)fore.gateway,(string)fore.nextjump);
            }
            else
            {
                setroute(RTACTION_ADD,(string)fore.dest,(string)fore.mask,(string)fore.gateway,(string)fore.nextjump);
            }
        }
        else
        {
            setroute(RTACTION_ADD,(string)fore.dest,(string)fore.mask,(string)fore.gateway,(string)fore.nextjump);
        }
    }
    

    return 1;

}
int main(int argc,char** argv)
{
    
}